<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#canvas {
				background: #fff;
				border: 1px solid #ccc
			}
		</style>
	</head>
	<body>
		<canvas id="canvas" width="700" height="300"></canvas>
		<script>
			var c = document.getElementById("canvas");
			var ctx = c.getContext("2d");

			ctx.rect(10, 10, c.width - 20, c.height - 20);
			ctx.fillStyle = "gray";
			ctx.fill();

			ctx.strokeStyle = "red";
			ctx.beginPath();
			ctx.arc(100, 75, 50, 0, 2 * Math.PI);
			ctx.stroke();

			ctx.strokeStyle = "blue";
			ctx.beginPath();
			ctx.rect(200, 100, 200, 150);
			ctx.stroke();


			let oImgData = ctx.getImageData(190, 90, 220, 170);
			let oCanvas = document.createElement("canvas");
			oCanvas.width = 220;
			oCanvas.height = 170;
			let oCtx = oCanvas.getContext("2d");
			oCtx.putImageData(oImgData, 0, 0);
			let oGrayImg = new Image();
			oGrayImg.src = oCanvas.toDataURL();

			let divHint = document.createElement("div");
			divHint.innerHTML = "截取的矩形：";
			document.body.appendChild(divHint);
			document.body.appendChild(oGrayImg);
			
			clearblankimg(oCanvas.toDataURL())
			
			function clearblankimg(imgData) {

				var img = new Image(); //创建图片对象
				img.src = imgData;
				img.onload = function() {
					var c = document.createElement('canvas'); //创建处理画布对象
					var ctx = c.getContext('2d');
					c.width = img.width;
					c.height = img.height;
					ctx.drawImage(img, 0, 0); //绘制
					var imgData = ctx.getImageData(0, 0, c.width, c.height).data; //读取图片数据
					var lOffset = c.width,
						rOffset = 0,
						tOffset = c.height,
						bOffset = 0;
					for (var i = 0; i < c.width; i++) {
						for (var j = 0; j < c.height; j++) {
							var pos = (i + c.width * j) * 4
							if (imgData[pos] == 255 || imgData[pos + 1] == 255 || imgData[pos + 2] == 255 || imgData[pos +
								3] == 255) {
								bOffset = Math.max(j, bOffset); // 找到有色彩的最下端
								rOffset = Math.max(i, rOffset); // 找到有色彩的最右端
								tOffset = Math.min(j, tOffset); // 找到有色彩的最上端
								lOffset = Math.min(i, lOffset); // 找到有色彩的最左端
							}
						}
					}
					lOffset++;
					rOffset++;
					tOffset++;
					bOffset++;
					var x = document.createElement("canvas"); //创建处理后画布对象
					x.width = rOffset - lOffset;
					x.height = bOffset - tOffset;
					var xx = x.getContext("2d");
					xx.drawImage(img, lOffset, tOffset, x.width, x.height, 0, 0, x.width, x.height); //绘制

					console.log(x.toDataURL()); //得到最终裁剪出来的base64

				}

			}
		</script>
	</body>
</html>
